﻿using DataAchive.ExContr;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Forms;
using DataAchive.Common;
using DataAchive.Model.Excel.Export;
using DataAchive.Helper;
using NPOI.SS.Formula.Functions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
using System.Threading;

namespace DataAchive
{
    /// <summary>
    /// PictureClassifyWindow.xaml 的交互逻辑
    /// </summary>
    public partial class PictureClassifyWindow : Window
    {
        internal WhereQ GetWhereQ {  get; set; }
        internal string Address {  get; set; }
        internal ImgClassifyConfig ImgClassifyConfig = new ImgClassifyConfig();
        public PictureClassifyWindow()
        {
            InitializeComponent();           
            ContentRendered += PictureClassifyWindow_ContentRendered;
                     
           
        }

        private void PictureClassifyWindow_ContentRendered(object sender, EventArgs e)
        {
            var jImgConf = JConfig.ReadConf();
            SetConfigPath(jImgConf);
        }


        private void SetConfigPath(ImgClassifyConfig jImgConf)
        {
            if (jImgConf.UseConfig)
            {
                if (!string.IsNullOrWhiteSpace(jImgConf.ElSourceDir))
                {                
                    ImgClassifyConfig.ElSourceDir = jImgConf.ElSourceDir.Trim();
               
                    elSourceFolder.Text = jImgConf.ElSourceDir.Trim();
                }
                if (!string.IsNullOrWhiteSpace(jImgConf.ViSourceDir))
                {                    
                    ImgClassifyConfig.ViSourceDir = jImgConf.ViSourceDir.Trim();
                    viSourceFolder.Text =jImgConf.ViSourceDir.Trim();
                }
                if (!string.IsNullOrWhiteSpace(jImgConf.VbSourceDir))
                {                    
                    ImgClassifyConfig.VbSourceDir = jImgConf.VbSourceDir.Trim();
                    vbSourceFolder.Text = jImgConf.VbSourceDir.Trim();
                }
                 if (!string.IsNullOrWhiteSpace(jImgConf.ElDesDir))
                {
                    ImgClassifyConfig.ElDesDir = jImgConf.ElDesDir.Trim();
                    elDestinationFolder.Text = jImgConf.ElDesDir.Trim();

                }
                 if (!string.IsNullOrWhiteSpace(jImgConf.ViDesDir))
                {
                    ImgClassifyConfig.ViDesDir = jImgConf.ViDesDir.Trim();
                    viDestinationFolder.Text = jImgConf.ViDesDir.Trim();

                }
                 if (!string.IsNullOrWhiteSpace(jImgConf.VbDesDir))
                {
                    ImgClassifyConfig.VbDesDir = jImgConf.VbDesDir.Trim();
                    vbDestinationFolder.Text = jImgConf.VbDesDir.Trim();
                }

                 ImgClassifyConfig.UseConfig = jImgConf.UseConfig;
                 ImgClassifyConfig.OverDays = jImgConf.OverDays>0? jImgConf.OverDays: ImgClassifyConfig.OverDays;
            }
        }

        private void elSourceBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            var dialogResult = dialog.ShowDialog();
            if (dialogResult == System.Windows.Forms.DialogResult.Cancel)
            {                
                return;
            }

            if (!string.IsNullOrEmpty(dialog.SelectedPath))
            {
                ImgClassifyConfig.ElSourceDir = dialog.SelectedPath.Trim();
                elSourceFolder.Text = dialog.SelectedPath.Trim() ;
             
            }

            //SoftCommon.Log.Write("");
        }

        private void elDesBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            var dialogResult = dialog.ShowDialog();
            if (dialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            if (!string.IsNullOrEmpty(dialog.SelectedPath))
            {
                ImgClassifyConfig.ElDesDir = dialog.SelectedPath.Trim();
                elDestinationFolder.Text = dialog.SelectedPath.Trim();

            }

        }

        private void viSourceBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            var dialogResult = dialog.ShowDialog();
            if (dialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            if (!string.IsNullOrEmpty(dialog.SelectedPath))
            {
                ImgClassifyConfig.ViSourceDir = dialog.SelectedPath.Trim();
                viSourceFolder.Text = dialog.SelectedPath.Trim();
            }

        }

        private void viDesBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            var dialogResult = dialog.ShowDialog();
            if (dialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            if (!string.IsNullOrEmpty(dialog.SelectedPath))
            {
                ImgClassifyConfig.ViDesDir = dialog.SelectedPath.Trim();
                viDestinationFolder.Text = dialog.SelectedPath.Trim();
            }

        }

        private void vbSourceBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            var dialogResult = dialog.ShowDialog();
            if (dialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            if (!string.IsNullOrEmpty(dialog.SelectedPath))
            {
                ImgClassifyConfig.VbSourceDir = dialog.SelectedPath.Trim();
                vbSourceFolder.Text = dialog.SelectedPath.Trim();
            }

        }

        private void vbDesBrowse_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
            var dialogResult = dialog.ShowDialog();
            if (dialogResult == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }

            if (!string.IsNullOrEmpty(dialog.SelectedPath))
            {
                ImgClassifyConfig.VbDesDir = dialog.SelectedPath.Trim();
                vbDestinationFolder.Text = dialog.SelectedPath.Trim();
            }

        }

        private void classifyPicBtn_Click(object sender, RoutedEventArgs e)
        {
            #region 按钮
            classifyPicBtn.IsEnabled = false;
            classifyPicBtn.Content = "分类中";
            richRizhi.Document.Blocks.Clear();
            richRizhi.Document.Blocks.Add(new Paragraph(new Run($"{DateTime.Now} ->开始分类.")));
            richRizhi.Document.Blocks.Add(new Paragraph(new Run($"{DateTime.Now} ->正在分类中.....")));
            //面板提示
            #endregion

            try
            {
                JConfig.WriteConf(ImgClassifyConfig);
           
                Task.Run(() => {
                    var listColRow = GetColRowReports();
                    if(listColRow==null|| listColRow.Count == 0)
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            richRizhi.Document.Blocks.Add(new Paragraph(new Run($"{DateTime.Now} ->未获取到数据库条码信息，流程结束！")));
                        }));
                        return;
                    }
                    ImgClassifyFunc.ClassfiyPicture(ImgClassifyConfig, listColRow);
                });
               

            }
            catch (Exception ex)
            {

               SoftCommon.Log.Write(ex);
            }
            finally
            {
                #region 按钮
                classifyPicBtn.IsEnabled = true;
                classifyPicBtn.Content = "开始分类";
                richRizhi.Document.Blocks.Add(new Paragraph(new Run($"{DateTime.Now} ->分类结束.")));
                #endregion
            }
        }


        private List<ColRowReport> GetColRowReports()
        {
            try
            {
                var dstail = ReportHelper.GetColRowReportInfo(GetWhereQ, Address);
                var dtval = ReportHelper.DetailReportTrans(dstail.Tables[0]);
                var lsresult = ReportHelper.DicColRowToList(dtval);
                lsresult.ForEach(x =>
                {
                    // var min = FindMinTime(x.ElCreateTime,x.VICreateTime,x.VBCreateTime);
                    var min_max = ReportShow.FindMaxTime(x.ElCreateTime, x.VICreateTime, x.VBCreateTime);
                    var max = ReportShow.FindMaxTime(x.ElFinishTime, x.VIFinishTime, x.VBFinishTime);
                    if (min_max == DateTime.MinValue || max == DateTime.MinValue)
                    {

                    }
                    else
                    {
                        x.HumanJudgeTime = max - min_max;
                    }
                    var direc = ReportShow.isDirectRes(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    x.IsDirect = direc ? "是" : "否";
                    if (direc)
                    {
                        x.HumanJudgeTime = TimeSpan.Zero;
                    }
                    int aiR = ReportShow.noNullResult(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult);
                    int RenR = ReportShow.noNullResult(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult);
                    if (aiR == RenR)
                    {
                        if (aiR == 1)
                        {
                            x.LouJianOrGuopan = ReportShow.louWu(
                                ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0]
                                );
                        }
                        else if (aiR == 2)
                        {
                            x.LouJianOrGuopan = ReportShow.louWu(
                              ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                              ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1]
                              );
                        }
                        else if (aiR == 3)
                        {
                            x.LouJianOrGuopan = ReportShow.louWu(
                              ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[0],
                                ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[1],
                                 ReportShow.noNullVal(x.ElAiDetectResult, x.VIAiDetectResult, x.VBAiDetectResult)[2],
                              ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[0],
                                 ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[1],
                                   ReportShow.noNullVal(x.ElHumanDetectResult, x.VIHumanDetectResult, x.VBHumanDetectResult)[2]
                              );
                        }
                    }

                    List<string> aielInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ElAiDetectInfo))
                    {
                        string[] allQx = x.ElAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aielInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aielInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aielInfoList = aielInfoList.Distinct().ToList();
                    aielInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ElAiDetectInfo = string.Join(",", aielInfoList);

                    List<string> aiviInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.ViAiDetectInfo))
                    {
                        string[] allQx = x.ViAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aiviInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aiviInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aiviInfoList = aiviInfoList.Distinct().ToList();
                    aiviInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.ViAiDetectInfo = string.Join(",", aiviInfoList);

                    List<string> aivbInfoList = new List<string>();

                    if (!string.IsNullOrWhiteSpace(x.VBAiDetectInfo))
                    {
                        string[] allQx = x.VBAiDetectInfo.Split(' ');
                        foreach (var item in allQx)
                        {
                            var shuzu = item.Split(':');
                            if (shuzu.Length == 2)
                            {
                                aivbInfoList.Add(shuzu[1]);
                            }
                            else if (shuzu.Length > 2)
                            {
                                SoftCommon.Log.Write($"缺陷是这个格式，可能有误:{item}");
                                aivbInfoList.Add(shuzu[1]);
                            }
                        }
                    }
                    aivbInfoList = aivbInfoList.Distinct().ToList();
                    aivbInfoList.RemoveAll(info => string.IsNullOrWhiteSpace(info));
                    x.VBAiDetectInfo = string.Join(",", aivbInfoList);

                });

                lsresult.ForEach(x => {
                    if (x.HumanJudgeTime != TimeSpan.Zero && string.IsNullOrWhiteSpace(x.LouJianOrGuopan))
                    {
                        x.LouJianOrGuopan = "NG";
                    }

                });
                return lsresult;
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(ex.Message);
            }

            return null;
          
        }
    }
}
